package com.it.commicity.service.impl.zy;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.commicity.common.Result;
import com.it.commicity.domain.po.*;
import com.it.commicity.domain.requestPass.Room;
import com.it.commicity.domain.vo.RoomVo;
import com.it.commicity.domain.vo.buildingAndUnit.BuildingAndUnit;
import com.it.commicity.domain.vo.buildingAndUnit.Unit;
import com.it.commicity.mapper.zy.ZyRoomMapper;
import com.it.commicity.service.sys.ISysDictDataService;
import com.it.commicity.service.zy.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.commicity.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 房间  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-11
 */
@Service
public class ZyRoomServiceImpl extends ServiceImpl<ZyRoomMapper, ZyRoom> implements IZyRoomService {
    @Autowired
    private ZyRoomMapper roomMapper;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private IZyUnitService zyUnitService;
    @Autowired
    private IZyBuildingService zyBuildingService;
    @Autowired
    private UUIDUtil uuidUtil;
    @Autowired
    private IZyOwnerRoomService ownerRoomService;
    @Autowired
    private IZyOwnerRoomRecordService roomRecordService;

    //    @Autowired
//    private IZyRoomService roomService;
    @Override
    public Result getRoomPage(Room room) {
        Page<RoomVo> page = new Page<>(room.getPageNum(), room.getPageSize());
        Page<RoomVo> roomPage = roomMapper.getRoomPage(page, room);
        if (roomPage.getRecords().size() <= 0) {
            return Result.fail("暂时没有数据");
        }
        List<SysDictData> dictDataList = dictDataService.getLabelListByTypes("zy_room_state", "zy_house_state");
        for (int i = 0; i < roomPage.getRecords().size(); i++) {
            for (int j = 0; j < dictDataList.size(); j++) {
                if (roomPage.getRecords().get(i).getRoomStatus().equals(dictDataList.get(j).getDictValue())) {
                    roomPage.getRecords().get(i).setRoomStatus(dictDataList.get(j).getDictLabel());
                }
                if (roomPage.getRecords().get(i).getRoomHouseType().equals(dictDataList.get(j).getDictValue())) {
                    roomPage.getRecords().get(i).setRoomHouseType(dictDataList.get(j).getDictLabel());
                }
            }
        }
        return Result.success(roomPage);
    }

    @Override
    public Result getZyBuildingAndUnit(String communityId) {
        //查询某一区的所有单元
        LambdaQueryWrapper<ZyUnit> q1 = new LambdaQueryWrapper<>();
        q1.eq(ZyUnit::getCommunityId, communityId);
        List<ZyUnit> unitList = zyUnitService.list(q1);
        //查询某一区的所有楼栋
        LambdaQueryWrapper<ZyBuilding> q2 = new LambdaQueryWrapper<>();
        q2.eq(ZyBuilding::getCommunityId, communityId);
        List<ZyBuilding> zyBuildings = zyBuildingService.list(q2);
        ArrayList<BuildingAndUnit> buildingAndUnits = new ArrayList<>();
        for (int i = 0; i < zyBuildings.size(); i++) {
            BuildingAndUnit buildingAndUnit = new BuildingAndUnit();
            buildingAndUnit.setValue(zyBuildings.get(i).getBuildingId());
            buildingAndUnit.setLabel(zyBuildings.get(i).getBuildingName());
            ArrayList<Unit> units = new ArrayList<>();
            for (int j = 0; j < unitList.size(); j++) {
                if (unitList.get(j).getBuildingId().equals(zyBuildings.get(i).getBuildingId())) {
                    units.add(new Unit(unitList.get(j).getUnitId(), unitList.get(j).getUnitName()));
                }
            }
            buildingAndUnit.setChildren(units);
            buildingAndUnits.add(buildingAndUnit);
        }
        return Result.success(buildingAndUnits);
    }

    @Override
    public List<RoomVo> getExportData(ArrayList<Long> roomIds, Long communityId) {
        List<RoomVo> zyRooms = null;
        if (roomIds.size() <= 0) {
            zyRooms = roomMapper.selectListByCommunityId(communityId);
        } else {
            zyRooms = roomMapper.selectListByListRoomId(roomIds);
        }
        return zyRooms;
    }

    @Override
    public Result updateAndSaveZyRoom(ZyRoom zyRoom) {
        List<ZyRoom> list = roomMapper.selectList(null);
        //判断添加或修改时，是否已存在相同的房号（同一栋同一单元同一房号）
        //添加：不能添加已存在（相同）的房号（同一栋同一单元同一房号）
        //修改：不能修改为已存在（相同）的房号
        for (ZyRoom room : list) {
            //判断zyRoom是否有room_id
            if (zyRoom.getRoomId() != null && !"".equals(zyRoom.getRoomId())) {
                //若数据库id跟前端id一样做修改，跳出本次循环
                //如果roomId相同，说明是自己，跳过检查
                if (zyRoom.getRoomId().equals(room.getRoomId())) {//跳过自身校验
                    continue;
                }
            }
            //检查是否是同一栋同一单元同一房号，如果是修改和添加失败，不可能同时出现同一栋同一单元同一房号
            if (zyRoom.getCommunityId().equals(room.getCommunityId())) {
                //是否在同一栋
                if (zyRoom.getBuildingId().equals(room.getBuildingId())) {
                    //是否在同一单元
                    if (zyRoom.getUnitId().equals(room.getUnitId())) {
                        //是否房间名相同
                        if (zyRoom.getRoomName().equals(room.getRoomName())) {
                            //修改或添加失败,在同一小区,同一栋,同一单元房间名已存在
                            return Result.success("1", null);
                        }
                    }
                }
            }
        }
        //是否修改操作
//        boolean i;
        int i;
        if (zyRoom.getRoomId() != null && !"".equals(zyRoom.getRoomId())) {
            //修改
            System.err.println("zyRoomServImpl-updateAndSaveZyRoom->" + zyRoom);
            i = roomMapper.updateById(zyRoom);
        } else {
            //添加操作
            String roomCode = uuidUtil.getRoomCode();
            System.out.println("zyRoomSerImpl-roomCode" + roomCode);
            zyRoom.setRoomCode(roomCode);
            i = roomMapper.insert(zyRoom);
        }
        if (i <= 0) {
            return Result.success("1", null);
        }
        return Result.success("成功");
    }

    @Override
    public Result deleteByRoomIds(ArrayList<Long> roomIds) {
        //删除之前判断是否存在已经出售的房屋
        List<RoomVo> roomVoList = roomMapper.selectListByListRoomId(roomIds);
        for (RoomVo room : roomVoList) {
            if (!room.getRoomStatus().equals("none")) {
                return Result.fail("存在已被业主购买的房屋！不可删除！");
            }
        }
        roomMapper.deleteBatchIds(roomIds);
        //删除关联的业主-房间关系：
        LambdaQueryWrapper<ZyOwnerRoom> lqw = new LambdaQueryWrapper<>();
        lqw.in(ZyOwnerRoom::getRoomId, roomIds);
        ownerRoomService.remove(lqw);
        //删除关联的业主-房间历史记录：
        LambdaQueryWrapper<ZyOwnerRoomRecord> lqw2 = new LambdaQueryWrapper<>();
        lqw2.in(ZyOwnerRoomRecord::getRoomId, roomIds);
        roomRecordService.remove(lqw2);
        return Result.success("删除成功！", null);
    }
}
